﻿using System;
using System.Collections.Generic;
using System.Data.Entity.SqlServer;
using System.Linq;
using System.Net.Mime;
using WebApiAttributeDemo.DAL.Entities;

namespace WebApiAttributeDemo.DAL.Repository
{
    public class BlogRepository : IBlogRepository
    {
        private readonly BlogContext _context;

        public BlogRepository()
        {
            _context = new BlogContext();
        }

        public IEnumerable<BlogPost> GetAll()
        {
            return _context.BlogPosts;
        }

        public BlogPost GetById(long id)
        {

            return _context.BlogPosts.SingleOrDefault(x => x.Id == id);
        }

        public IEnumerable<BlogPost> GetByDate(DateTime date)
        {
            return _context.BlogPosts.Where(x => SqlFunctions.DateDiff("dd", date, x.ModifiedOn) == 0);
        }

        public IEnumerable<BlogPost> GetByAuthor(string author)
        {
            return _context.BlogPosts.Where(x => x.Author == author);
        }

        public void Delete(long id)
        {
            var post = GetById(id);
            _context.BlogPosts.Remove(post);
            _context.SaveChanges();
        }

        public void Add(BlogPost post)
        {
            post.CreatedOn = DateTime.Now;
            post.ModifiedOn = DateTime.Now;
            _context.BlogPosts.Add(post);
            _context.SaveChanges();
        }

        public void Update(BlogPost post)
        {
            post.ModifiedOn = DateTime.Now;
            var existing = GetById(post.Id);
            if (existing != null)
            {
                _context.Entry(existing).CurrentValues.SetValues(post);
                _context.SaveChanges();
            }
            _context.SaveChanges();
        }
    }
}